package org.dtrd.modules.content.tags.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.content.tags.entity.bean.*;
import org.dtrd.modules.content.tags.entity.request.TagCategoryListRequest;
import org.dtrd.modules.content.tags.entity.request.TagCategoryPageRequest;
import org.dtrd.modules.content.tags.entity.request.TagsListRequest;
import org.dtrd.modules.content.tags.entity.request.TagsPageRequest;
import org.dtrd.modules.content.tags.service.IDtrdExtEmsYwTagCategoryService;
import org.dtrd.modules.content.tags.service.IDtrdExtEmsYwTagsService;
import org.dtrd.modules.patient.entity.request.PatientTagRequest;
import org.dtrd.modules.patient.service.IDtrdRlPatientTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_OPERATION_FAILURE;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

/**
 * <p>
 * 标签分类 前端控制器
 * </p>
 *
 * @author QR
 * @since 2022-03-15
 */
@Api(tags = "标签管理")
@ApiSort(11)
@RestController
@RequestMapping("/tag/")
public class TagManageController extends BaseController {

    @Autowired
    private IDtrdExtEmsYwTagCategoryService tagCategoryService;
    @Autowired
    private IDtrdExtEmsYwTagsService tagsService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private IDtrdRlPatientTagService patientTagRlService;


    @ApiOperation(value = "查询标签分类详情", response = TagCategoryDetail.class, hidden = true)
    @GetMapping("/category/get")
    public Result<?> getTagCategory(@RequestParam Integer id) {
        TagCategoryDetail info = tagCategoryService.getTagCategory(id);
        String logContent = String.format("查询标签分类详情，查询id：%d", id);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(info);
    }

    @ApiOperation(value = "查询标签分类列表", response = TagCategoryListInfo.class)
    @PostMapping("/category/list")
    public Result<?> getTagCategoryList(@RequestBody TagCategoryListRequest request) {
        List<TagCategoryListInfo> list = tagCategoryService.getTagCategoryList(request);
        String logContent = String.format("查询标签分类列表, 查询条件: %s", request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }

    @ApiOperation(value = "分页查询标签分类列表", response = TagCategoryListInfo.class)
    @PostMapping("/category/page")
    public Result<?> getTagCategoryList(@RequestBody TagCategoryPageRequest request) {
        handlePageRequest(request);
        IPage<TagCategoryListInfo> page = tagCategoryService.pageTagCategory(request);
        String logContent = String.format("分页查询标签分类列表, 查询条件: %s", request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        JSONObject result = new JSONObject();
        result.put("recordList", page.getRecords());
        result.put("totalPage", page.getPages());
        result.put("count", page.getTotal());
        return Result.OK(result);
    }

    public final static Integer pid = 0;

    @ApiOperation("新增或修改标签分类")
    @PostMapping("/category/saveOrUpdate")
    public Result<?> saveOrUpdateTagCategory(@RequestBody TagCategoryDetail dto) {
        String categoryName = dto.getCategoryName();
        if (StrUtil.isBlank(categoryName)) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer categoryPid = dto.getCategoryPid();
        if (categoryPid == null) {
            dto.setCategoryPid(pid);
        }
        boolean result = tagCategoryService.saveOrUpdateTagCategory(dto);
        String logContent = String.format("新增或修改标签分类, 标签分类id: %d, 分类名称: %s", dto.getDataId(), categoryName);
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除标签分类")
    @DeleteMapping("/category/remove")
    public Result<?> removeTagCategory(@RequestParam Integer tagCategoryId) {
        if (isIntParamInvalid(tagCategoryId)) {
            return error(STATE_PARAMS_MISSING);
        }
        if (tagsService.hasLinkTag(tagCategoryId)) {
            return Result.error("该分类已关联标签无法删除");
        }
        boolean result = tagCategoryService.removeTagCategory(tagCategoryId);
        String logContent = String.format("删除标签分类, 删除id: %d", tagCategoryId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "通过标签分类查询查询标签列表", response = TagsListInfo.class)
    @PostMapping("list")
    public Result<?> getTagsList(@RequestBody TagsListRequest request){
        Integer tagType = request.getTagType();
        List<TagsListInfo> list = tagsService.getTagsList(request.getTagName(),tagType);
        String logContent = String.format("查询标签列表, 查询条件: %s", request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }

    @ApiOperation(value = "查询某个总级分类下的所有标签列表", response = TagGroupInfo.class, notes = "默认为pid为患者分类(17)，还有一个是内容(18)")
    @GetMapping("categoryList")
    public Result<?> getTagsListByPid(@RequestParam(value = "pid", required = false, defaultValue = "17") Integer pid){
        List<TagGroupInfo> list = tagsService.listTags(pid);
        String logContent = String.format("查询标签列表, 查询标签pid: %d", pid);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }

    @ApiOperation(value = "分页查询标签列表", response = TagsListInfo.class, hidden = true)
    @PostMapping("page")
    public Result<?> getTagsList(@RequestBody TagsPageRequest request){
        handlePageRequest(request);
        IPage<TagsListInfo> page = tagsService.pageTags(request);
        String logContent = String.format("分页查询标签列表, 查询条件: %s", request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        JSONObject result = new JSONObject();
        result.put("recordList", page.getRecords());
        result.put("totalPage", page.getPages());
        return Result.OK(result);
    }

    @ApiOperation("新增或修改标签")
    @PostMapping("saveOrUpdate")
    public Result<?> saveOrUpdateTags(@RequestBody TagsDetail dto){
        String tagName = dto.getTagName();
        if (StrUtil.isBlank(tagName)) {
            return error(STATE_PARAMS_MISSING);
        }
        boolean result = tagsService.saveOrUpdateTags(dto);
        String logContent = String.format("新增或修改标签, 标签名字: %s, 标签id, %d", tagName, dto.getTagId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("设置绑定患者")
    @PostMapping("/bindPatient")
    public Result<?> bindPatientTag(@RequestBody PatientTagRequest request){
        Integer patientId = request.getPatientId();
        if (patientId == null) {
            return error(STATE_PARAMS_MISSING);
        }
        List<Integer> tagIds = request.getTagIds();
        boolean result = patientTagRlService.saveOrUpdatePatientTagRelation(patientId, tagIds);
        String logContent = String.format("设置患者标签, 标签id: %s, 患者id, %d", tagIds.toString(), patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除标签")
    @DeleteMapping("remove")
    public Result<?> removeTags(@RequestParam Integer tagId){
        boolean result = tagsService.removeTags(tagId);
        String logContent = String.format("删除标签, 删除id: %d", tagId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
}
